﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.Framework;
using System.Reflection;
using System.IO;
using IMeem.Model;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using IMeem.BO;
using System.Windows.Media.Animation;
using IMeem.ViewModels;
using System.ComponentModel;

namespace IMeem
{
    /// <summary>
    /// Interaction logic for Magnet.xaml
    /// </summary>
    public partial class Magnet : UserControl , IMagnet, IRequiresStorage, ICanDrag
    {
        Storyboard _showPlayerSB;
        Storyboard _hidePlayerSB;
        Storyboard _startLoadingModeSB;
        Storyboard _endLoadingModeSB;
        Storage _storage;
        bool _canDrag = true;

        public Magnet()
        {
            InitializeComponent();
            _searchTbx.GotFocus += new RoutedEventHandler(_searchTbx_GotFocus);
            _searchTbx.KeyUp += new KeyEventHandler(_searchTbx_KeyUp);
            _resultsLbx.MouseDoubleClick+=new MouseButtonEventHandler(_resultsLbx_MouseDoubleClick);
            _showPlayerSB = this.Resources["ShowPlayer"] as Storyboard;
            _hidePlayerSB = this.Resources["HidePlayer"] as Storyboard;
            _startLoadingModeSB = this.Resources["StartLoadingMode"] as Storyboard;
            _endLoadingModeSB = this.Resources["EndLoadingMode"] as Storyboard;
            _browser.MouseEnter += new MouseEventHandler(_browser_MouseEnter);
            _browser.MouseLeave += new MouseEventHandler(_browser_MouseLeave);
            _preLoader.Start();
            ((IMeemViewModel)this.DataContext).PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Magnet_PropertyChanged);
            ((IMeemViewModel)this.DataContext).SearchAsyncStarted += new IMeemViewModel.SearchAsyncStartedHandler(Magnet_SearchAsyncStarted);
        }

        void Magnet_SearchAsyncStarted(string keyword)
        {
            _startLoadingModeSB.Seek(new TimeSpan(0, 0, 0));
            this.BeginStoryboard(_startLoadingModeSB);
        }

        void Magnet_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "LatestSearchResults")
            {
                _endLoadingModeSB.Seek(new TimeSpan(0, 0, 0));
                this.BeginStoryboard(_endLoadingModeSB);
            }            
        }

        void _browser_MouseLeave(object sender, MouseEventArgs e)
        {
            _canDrag = true;
        }

        void _browser_MouseEnter(object sender, MouseEventArgs e)
        {
            _canDrag = false;
        }

        void _searchTbx_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                _okBt_Click(sender, e);
        }

        void _searchTbx_GotFocus(object sender, RoutedEventArgs e)
        {
            _searchTbx.Text = string.Empty;
        }      

        void _okBt_Click(object sender, RoutedEventArgs e)
        {
            IMeemViewModel iMeemViewModel = this.DataContext as IMeemViewModel;
            iMeemViewModel.SearchAsync(_searchTbx.Text, true);
        }

        private void NavigateToSong(SearchResult searchResult)
        {
            this.BeginStoryboard(_showPlayerSB);            

            string htmFilePath = System.IO.Path.Combine(_storage.StorageDirectory.FullName,  "Template.htm");
            if (File.Exists(htmFilePath))
                File.Delete(htmFilePath);

            CopyEmbededResourceOnDisk(System.IO.Path.GetFileName(htmFilePath), System.IO.Path.GetDirectoryName(htmFilePath));
            StreamReader file = File.OpenText(htmFilePath);
            string source = file.ReadToEnd();
            string value1 = GetFlashvarValue(searchResult.Flashvars, @"\u0026r\");
            source = source.Replace("INSERT_HERE1", value1);
            string value2 = GetFlashvarValue(searchResult.Flashvars, @"\u0026mids\");
            source = source.Replace("INSERT_HERE2", value2);
            file.Dispose();
            File.Delete(htmFilePath);
            string tempFile = System.IO.Path.GetTempFileName();
            string renamedTempFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(tempFile), System.IO.Path.GetFileNameWithoutExtension(tempFile) + ".htm");
            File.Copy(tempFile, renamedTempFile);
            File.Delete(tempFile);
            StreamWriter sw = new StreamWriter(renamedTempFile);
            sw.Write(source);
            sw.Flush();
            sw.Dispose();
            Uri uri = new Uri(renamedTempFile);
            _browser.Source = uri.AbsoluteUri;            
        }

        private string GetFlashvarValue(string flashVars, string key)
        {
            int startIndex = flashVars.IndexOf(key) + key.Length;
            int endIndex = flashVars.IndexOf(@"\", startIndex);
            string value = flashVars.Substring(startIndex, endIndex - startIndex);
            return value;
        }

        private void CopyEmbededResourceOnDisk(string resource, string path)
        {
            if (!File.Exists(System.IO.Path.Combine(path, resource)))
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                int count = 0;
                byte[] buffer = new byte[0x800];
                Assembly executingAssembly = Assembly.GetExecutingAssembly();
                using (Stream stream = executingAssembly.GetManifestResourceStream(string.Format("{0}.{1}.{2}", executingAssembly.GetName().Name, "HTML", resource)))
                {
                    using (FileStream stream2 = new FileStream(path + @"\" + resource, FileMode.Create, FileAccess.Write))
                    {
                        using (BinaryWriter writer = new BinaryWriter(stream2))
                        {
                            while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                writer.Write(buffer, 0, count);
                                writer.Flush();
                            }
                        }
                    }
                }
                buffer = null;
            }
        }

        #region IMagnet Members

        public string StoreID
        {
            get { return "{B04E6055-5CF8-43f6-B5A8-7CD66A59835F}"; }
        }

        public Panel GetBackSide()
        {
            throw new NotImplementedException();
        }

        public Panel GetFrontSide()
        {
            throw new NotImplementedException();
        }

        public BitmapImage Icon
        {
            get { return ResourcesAccess.GetBitmapImageFromResource(Assembly.GetExecutingAssembly(), "IMeem.Images.logo.png"); }
        }

        public string MagnetName
        {
            get { return "imeem"; }
        }

        public void Terminate()
        {
            
        }

        public BitmapImage Thumbnail
        {
            get { return ResourcesAccess.GetBitmapImageFromResource(Assembly.GetExecutingAssembly(), "IMeem.Images.thumb.png"); }
        }

        private void _resultsLbx_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }

        private void _resultsLbx_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (_resultsLbx.SelectedItem != null)
            {
                SearchResult searchResult = _resultsLbx.SelectedItem as SearchResult;
                Singletons s = new Singletons();
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += (a, b) =>
                    {
                        b.Result = s.Instances.Imeem.UpdateFlashvars(searchResult);
                    };
                bw.RunWorkerCompleted += (a, b) =>
                    {
                        if (b.Error == null)
                            NavigateToSong(b.Result as SearchResult);
                        else
                        {
                            ExceptionsManager.LogException("imeem", b.Error, true);
                        }
                    };
                bw.RunWorkerAsync();
                /*searchResult = s.Instances.Imeem.UpdateFlashvars(searchResult);
                NavigateToSong(searchResult);*/
            }
        }

        #endregion

        
        #region IRequiresStorage Members

        public void GetStorage(Storage storage)
        {
            _storage = storage;
        }

        public void SaveState()
        {
            
        }

        #endregion

        #region ICanDrag Members

        public bool CanDrag()
        {
            return _canDrag;
        }

        #endregion
    }
}
